<?php
/**
 * tmaic.com
 * ============================================================================
 * * 版权所有 2020-2030 tmaic，并保留所有权利。
 * 网站地址: http://www.tmaic.com；
 * ----------------------------------------------------------------------------
 * 这不是一个自由软件！您只能在不用于商业目的的前提下对程序代码进行修改和
 * 使用；不允许对程序代码以任何形式任何目的的再发布。
 * ============================================================================
 * $Author: pangxianfei
 * $email:421339244@qq.com
 * $phone:18929142226
 * $date 2020-11-13
 *前台公共基类
 */

namespace App\Http\Controllers;
use Illuminate\Support\Facades\Storage;
use Illuminate\Http\Request;
use Illuminate\View\View;
use Illuminate\Support\Facades\View as Iviews;
use App\Models\Navigation;
use App\Models\Column;
use App\Models\ColumnTranslation;
use Cache;

class BaseController extends Controller
{
    const PCTemplate = 'pc';
    const MTemplate = 'm';
    const DS = '/';
    //终端
    protected $iswap;
    //当前主题
    protected $theme;
    //是否为手机端
    protected $isMobile;
    //系统语言
    protected $syslang;
    //当前语言
    protected $locale;
    //当前操作方法
    protected $ispart;
    //当前路由
    protected $routeName;
    //当前栏目
    protected $column;
    //要转发的控制器
    protected $Controller;
    //要转发的方法
    protected $fuction;
    //当前模型
    protected $model;
    //当前栏目ID
    protected $columnid;
    //是否详情页进来的，标志
    protected $whetherColumn;
    //面包屑导航
    protected $crumb;
	//缓存时间
	protected $SYSCACHETIME;
    public function __construct()
    {
		$this->init();
        $this->columnInitData();
        $this->setTemplate();
    }
	
	protected function init(){
	$request  = new Request(); 	
 
        $this->isMobile 		= isMobile();
        $this->whetherColumn 	= 0;
        $this->ispart 			= [1 => "lists", 2 => "index", 3 => null];
        $this->routeName		= request()->route()->getName() ?? null;
        $this->syslang 			= app()->getLocale();
        $this->locale 			= $this->syslang;
        $this->theme 			= config('theme.theme', 'default');
		$this->SYSCACHETIME 	= webconfig('SYSCACHETIME');
	}

    public function setTemplate()
    {
        $this->iswap = (bool)webconfig('iswap');
    }

    /**出始化当前栏目
     * @param int|null $column
     */
    public function columnInitData(int $columnid = null)
    {

        empty($columnid)?$this->GetColumn():$this->InitColumn($columnid);
		
		if($this->column){

			$this->Controller 	= $this->column->model . "Controller";
			$this->fuction 		= $this->ispart[$this->column->ispart];
			$this->model 		= $this->column->model;
			$this->columnid 	= $this->column->column_mid;
		}
		
    }
    /**出始化栏目
     * @param int|columnid 栏目ID
     */
	
	public function InitColumn(int $columnid){
		
		$CacheKey = $this->routeName .'_'.lang(). '_children_class_' . $this->locale . '_' . $columnid;
		
		$this->column = Cache::remember($CacheKey, $this->SYSCACHETIME, function () use ($columnid) {
			return ColumnTranslation::with(['children', 'class'])->where('column_mid', $columnid)->where('locale', lang())->first();
			
		});
		$this->whetherColumn = 1;
	}
	
	
	public function GetColumn(){
		
        $this->column = Cache::remember($this->routeName . '_children_class_' . $this->locale, $this->SYSCACHETIME, function () {
            return ColumnTranslation::with(['children', 'class'])->where('routename', $this->routeName)->first();
        });
		
	}
	

    /**栏目列表
     * @param string|null $model
     * @return object
     */
    public function getColumnClass(string $model = null): object
    {
        return Cache::remember($this->locale . "_" . $model, $this->SYSCACHETIME, function () use ($model) {

            return ColumnTranslation::with(["children"])->when($model, function ($query) use ($model) {
                    return $query->where('model', $model);
                })->lang()->where('pid', 0)->orderBy('sort', 'asc')->get();
        });
    }

    /**面包屑导航
     * @param $column
     * @return array
     */
    public function crumb($column): array
    {
        $tree[] = $column;
        if ($column->pid == 0) return $tree;

        $row = Cache::remember($this->locale . "_crumb_" . $column->column_mid, $this->SYSCACHETIME, function () use ($column) {

            return $row = ColumnTranslation::lang()->where('sid', $column->pid)->first();

        });
        $tree[] = $row;

        while ($row["pid"] !== 0) {

            $row = Cache::remember($this->locale . "_crumb_while_" . $row->column_mid, $this->SYSCACHETIME, function () use ($row) {

                return ColumnTranslation::lang()->where('sid', $row->pid)->first();
            });

            $tree[] = $row;
        }
        return array_reverse($tree);
    }


    /**找出父类
     * @param $column
     * @param null $isSid
     * @return array
     */
    public function getTopClass($column, $isSid = null)
    {
        if ($column->pid == 0) return ['id' => $column->id, 'sid' => $column->sid, 'pid' => $column->sid, 'columnid' => $column->column_mid];
        //默认分类ID
        $pid = $column->pid;
        $columnid = $column->column_mid;
        $id = $column->id;
        $sid = $column->sid;
        $row = Cache::remember($this->locale . '_topClass_' . $column->column_mid, $this->SYSCACHETIME, function () use ($column) {
            return ColumnTranslation::lang()->where('sid', $column->sid)->first();
        });
        while ($row['pid']) {

            $row = Cache::remember($this->locale . '_topClass_while_' . $row->column_mid, $this->SYSCACHETIME, function () use ($row) {
                return ColumnTranslation::where(['locale' => lang(), 'sid' => $row->pid])->first();
            });

            $pid 		= $row->pid;
            $columnid	= $row->column_mid;
            $id 		= $row->id;
            $sid 		= $row->sid;
        }
        return $isSid ? $sid : ['id' => $id, 'sid' => $sid, 'pid' => $pid, 'columnid' => $columnid];
    }

    /**
     * @param $column
     * @return array
     */
    public function getChiClass($column): array
    {
        $columnArray[] = $column->column_mid;

        $row = Cache::remember($this->locale . '_ChiClass_' . $column->column_mid, $this->SYSCACHETIME, function () use ($column) {
            return $row = ColumnTranslation::lang()->where('pid', $column->sid)->get();
        });
        foreach ($row as $item) {
            $columnArray[] = $item->column_mid;
        }

        return $columnArray;
    }

    /**
     * @param array $data
     * @param null $view
     * @return \Illuminate\Contracts\View\View
     */
    public function view($data = [], $view = null)
    {
        $this->isMobile = $isMobile = isMobile();

        if ($this->column) {
            $data['seo_title'] 		= $this->column->seo_title;
            $data['keyword'] 		= $this->column->seo_key;
            $data['description'] 	= $this->column->description;
            view()->share('desc', $this->column->description);
            view()->share('seokey', $this->column->seo_key);
        }
        //为首页时
        if ($this->routeName == "home" || empty($this->column)) {
            $data['seo_title'] 		= siteconfig('seo_title');
            $data['keyword'] 		= siteconfig('keywords');
            $data['description'] 	= siteconfig('description');
        }

        //向模板抛出变量
        //当前栏目		
        view()->share('column', $this->column);
        //面包屑
        view()->share('crumb', $this->column ? $this->crumb($this->column) : "");
        //当前路由名
        view()->share('routename', $this->routeName);
        //当前模型
        view()->share('models', $this->column->model ?? "Home");

        if ($view) return Iviews::make($isMobile . $view, $data);

        $view = $this->getTemplateName();

		//return Iviews::make("theme::" . $view, $data);
		$view = Iviews::make("theme::" . $view, $data);

		return $path = request()->path()=="/"?"index.html":request()->path();
		Storage::disk('view')->put($path, $view->render());

		return $view;

 	
		
		
		
		
		
		
		
		
    }

    /**
     * @return string
     */
    public function getTemplateName(): string
    {
        //当前控制器
        $CurrentAction = substr(getCurrentAction()['controller'], 0, -10);
        $CurrentAction = $this->column->model ?? $CurrentAction;
        //当前操作
        $CurrentMethod = getCurrentAction()['method'];
        $CurrentMethod = $this->column ? ($this->ispart[$this->column->ispart] ?? $CurrentMethod) : $CurrentMethod;
        //详情页面
        if ($this->whetherColumn) $CurrentMethod = getCurrentAction()['method'];
        //模板文件名
        $fileName = strtolower($CurrentAction) . self::DS . strtolower($CurrentMethod);
        //模板文件
        $view = $this->isMobile && $this->iswap ? self::MTemplate . self::DS . $fileName : self::PCTemplate . self::DS . $fileName;

        return $view;
    }

 


}
